package com.inspur.cloud.service.dataspace;

import com.alibaba.fastjson.JSONObject;
import com.inspur.cloud.configuration.AmbariConfig;
import com.inspur.cloud.dao.ambari.ComponentDesiredStateDao;
import com.inspur.cloud.entity.ambari.ComponentDesiredStateEntity;
import com.inspur.cloud.entity.ambari.HostsEntity;
import com.inspur.cloud.service.ambari.ClustersService;
import com.inspur.cloud.service.ambari.ComponentDesiredStateService;
import com.inspur.cloud.service.ambari.HostsService;
import com.inspur.cloud.util.Base64Util;
import com.inspur.cloud.util.SSLCertificateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.List;

@Service
public class HttpService {

    @Autowired
    private AmbariConfig ambariConfig;
    private static Logger log = LoggerFactory.getLogger(HttpService.class);
    @Autowired
    ClustersService clustersService;
    @Autowired
    ComponentDesiredStateService componentDesiredStateService;
    @Autowired
    HostsService hostsService;
    @Autowired
    ComponentDesiredStateDao componentDesiredStateDao;

    public String doAmbariGet(URL url) {
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == 200) {
                StringBuffer sb = new StringBuffer();
                try (InputStream is = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "utf-8"))
                ) {
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line);
                    }
                    return sb.toString();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (ProtocolException e) {
            return "";
        } catch (MalformedURLException e) {
            return "";
        } catch (IOException e) {
            return "";
        }
        return "";
    }

    public boolean doAmbariPut(String path, JSONObject jsonObject) {
        boolean flag = false;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(ambariConfig.getAmbariUri() + path);
            //集群是否开启https
            if (ambariConfig.isAmbariServerUseSsl()) {
                SSLCertificateUtil.disableChecks();
                connection = (HttpsURLConnection) url.openConnection();

            } else {
                connection = (HttpURLConnection) url.openConnection();
            }
            log.info("url={},json={}",url.getPath(),jsonObject);
            connection.setRequestMethod("PUT");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestProperty("X-Requested-By", "view-capacity-scheduler");
            connection.setRequestProperty("Connection", "keep-alive");
            String authorization = "Basic " + Base64Util.getBase64(ambariConfig.getAmbariServerUser() + ":" + ambariConfig.getAmbariServerPass());
            connection.setRequestProperty("Authorization", authorization);
            connection.setRequestProperty("Content-Type", "text/plain; charset=UTF-8");
            connection.setRequestProperty("Host", ambariConfig.getAmbariUri().substring(8));
        } catch (ProtocolException e) {
//            return "";
        } catch (MalformedURLException e) {
//            return "";
        } catch (IOException e) {
//            return "";
        }
        String authorization = "Basic " + Base64Util.getBase64(ambariConfig.getAmbariServerUser() + ":" + ambariConfig.getAmbariServerPass());
        connection.setRequestProperty("Authorization", authorization);
        try (PrintWriter out = new PrintWriter(connection.getOutputStream())) {
            out.write(jsonObject.toString());
            out.flush();
            if (connection.getResponseCode() == 200) {
                flag = true;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }

    public boolean doAmbariPut(String path) {
        boolean flag = false;
        HttpURLConnection connection;
        try {
            URL url = new URL(ambariConfig.getAmbariUri() + path);
            System.out.println(ambariConfig.getAmbariUri() + path);
            //集群是否开启https
            if (ambariConfig.isAmbariServerUseSsl()) {
                SSLCertificateUtil.disableChecks();
                connection = (HttpsURLConnection) url.openConnection();

            } else {
                connection = (HttpURLConnection) url.openConnection();
            }
            connection.setRequestMethod("PUT");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestProperty("X-Requested-By", "view-capacity-scheduler");
            connection.setRequestProperty("Connection", "keep-alive");
            String authorization = "Basic " + Base64Util.getBase64(ambariConfig.getAmbariServerUser() + ":" + ambariConfig.getAmbariServerPass());
            connection.setRequestProperty("Authorization", authorization);
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setRequestProperty("Host", ambariConfig.getAmbariUri().substring(8));

            PrintWriter out = new PrintWriter(connection.getOutputStream());
            JSONObject jo = new JSONObject();
            jo.put("save", "true");
            out.write(jo.toString());
            out.flush();
            System.out.println(connection.getResponseCode());
            if (connection.getResponseCode() == 200) {
                flag = true;
            }
        } catch (ProtocolException e) {
//            return "";
        } catch (MalformedURLException e) {
//            return "";
        } catch (IOException e) {
//            return "";
        }
        return flag;
    }

    public boolean doRestartYarn(){
        boolean flag = false;
        String clusterName=clustersService.findClusterName();
        if(clusterName==null){
            log.error("clusterName==null");
            return false;
        }
        List<ComponentDesiredStateEntity> list=componentDesiredStateDao.findByComponentName("RESOURCEMANAGER");
        if(list.size()==0){
            return false;
        }
        String RESTART_RM_REQUEST_DATA ="{\"RequestInfo\": {\n" +
                "    \"command\":\"RESTART\",\n" +
                "    \"context\":\"\\u91cd\\u542f ResourceManager\",\n" +
                "    \"operation_level\": {\n" +
                "        \"level\":\"SERVICE\",\n" +
                "        \"cluster_name\":\"%s\",\n" +
                "        \"service_name\":\"YARN\"\n" +
                "        }\n" +
                "    },\n" +
                "    \"Requests/resource_filters\": [\n" +
                "        {\n" +
                "            \"service_name\":\"YARN\",\n" +
                "            \"component_name\":\"RESOURCEMANAGER\",\n" +
                "            \"hosts\":\"%s\"\n" +
                "        }\n" +
                "    ]\n" +
                "}\n";
        String json="";
        if(list.size()==1){//考虑主备情况
            ComponentDesiredStateEntity componentDesiredStateEntity=list.get(0);
            if(componentDesiredStateEntity==null){
                log.error("componentDesiredStateEntity==null");
                return false;}
            HostsEntity hostsEntity=hostsService.findByhostId(componentDesiredStateEntity.getHostId());
            if(hostsEntity==null){
                log.error("hostsEntity==null");
                return false;
            }
            String host=hostsEntity.getHostName();
            json=String.format(RESTART_RM_REQUEST_DATA, clusterName, host);
        }else if(list.size()==2){
            ComponentDesiredStateEntity componentDesiredStateEntity1=list.get(0);
            ComponentDesiredStateEntity componentDesiredStateEntity2=list.get(1);
            HostsEntity hostsEntity1=hostsService.findByhostId(componentDesiredStateEntity1.getHostId());
            if(hostsEntity1==null){
                log.error("hostsEntity1==null");
                return false;
            }
            HostsEntity hostsEntity2=hostsService.findByhostId(componentDesiredStateEntity2.getHostId());
            if(hostsEntity2==null){
                log.error("hostsEntity2==null");
                return false;
            }
            String host1=hostsEntity1.getHostName();
            String host2=hostsEntity2.getHostName();
            RESTART_RM_REQUEST_DATA ="{\"RequestInfo\": {\n" +
                    "    \"command\":\"RESTART\",\n" +
                    "    \"context\":\"\\u91cd\\u542f ResourceManager\",\n" +
                    "    \"operation_level\": {\n" +
                    "        \"level\":\"SERVICE\",\n" +
                    "        \"cluster_name\":\"%s\",\n" +
                    "        \"service_name\":\"YARN\"\n" +
                    "        }\n" +
                    "    },\n" +
                    "    \"Requests/resource_filters\": [\n" +
                    "        {\n" +
                    "            \"service_name\":\"YARN\",\n" +
                    "            \"component_name\":\"RESOURCEMANAGER\",\n" +
                    "            \"hosts\":\"%s\"\n" +
                    "        },\n" +
                    "{\n" +
                    "          \"service_name\":\"YARN\",\n" +
                    "            \"component_name\":\"RESOURCEMANAGER\",\n" +
                    "            \"hosts\":\"%s\"\n" +
                    "        }\n" +
                    "    ]\n" +
                    "}\n";
            json=String.format(RESTART_RM_REQUEST_DATA, clusterName, host1,host2);
        }

        HttpURLConnection connection;
        try {
            URL url = new URL(ambariConfig.getAmbariUri() + "/api/v1/clusters/"+clusterName+"/requests");
            //集群是否开启https
            if (ambariConfig.isAmbariServerUseSsl()) {
                SSLCertificateUtil.disableChecks();
                connection = (HttpsURLConnection) url.openConnection();

            } else {
                connection = (HttpURLConnection) url.openConnection();
            }
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("X-Requested-By", "X-Requested-By");
            connection.setRequestProperty("Connection", "keep-alive");
            String authorization = "Basic " + Base64Util.getBase64(ambariConfig.getAmbariServerUser() + ":" + ambariConfig.getAmbariServerPass());
            connection.setRequestProperty("Authorization", authorization);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
            connection.setRequestProperty("Host", ambariConfig.getAmbariUri().substring(8));

            PrintWriter out = new PrintWriter(connection.getOutputStream());
            out.write(json);
            out.flush();
            log.info("restart ambari json={},code={}",json,connection.getResponseCode());
            if (connection.getResponseCode() == 200) {
                flag = true;
            }
        }  catch (Exception e) {
            log.error("",e);
        }
        return flag;
    }
}
